package com.zhugang.week01;

/**
 * @program algorithms
 * @description: ipAnaly2
 * @author: chanzhugang
 * @create: 2022/05/19 22:38
 */
public class IpAnaly2 {

    public static void main(String[] args) {
        IpAnaly2 ipAnaly2 = new IpAnaly2();

        String ip = "123.9 2.2.34";
        boolean valid = ipAnaly2.check(ip);
        System.out.println(valid);
    }

    /**
     * IP地址解析： 123.92.2.34
     * 字符串转数字：digit = digit * 10 + (c - '0');
     *
     * @param ip
     * @return
     */
    public boolean check(String ip) {
        // 按.分割称4段，每段校验规则一样

        // 前置空格、 只能是数字、 大小在0-255之间、 中间不能有空格
        if (ip == null) {
            return false;
        }
        String[] ipSegments = ip.split("\\.");
        if (ipSegments.length != 4) {
            return false;
        }
        for (String ipSegment : ipSegments) {
            boolean valid = checkSegment(ipSegment);
            if (!valid) {
                return false;
            }
        }
        return true;
    }

    private boolean checkSegment(String ipSegment) {
        int n = ipSegment.length();
        int i = 0;
        while (i < n && ipSegment.charAt(i) == ' ') {
            i++;
        }
        if (i == n) {
            return false;
        }
        int digit = 0;
        while (i < n && ipSegment.charAt(i) != ' ') {
            char c = ipSegment.charAt(i);
            if (c < '0' || c > '9') {
                return false;
            }
            // 将字符转为整数
            digit = digit * 10 + (c - '0');
            if (digit > 255) {
                return false;
            }
            i++;
        }
        while (i < n) {
            // 后置空格 如： "123 4"
            char c = ipSegment.charAt(i);
            if (c != ' ') {
                // 空格后面又有非空格字符
                return false;
            }
            i++;
        }
        return true;
    }


}